package com.message.Baidu_ai_API.service.impl;

import com.message.Baidu_ai_API.Enum.PicStyle;
import com.message.Baidu_ai_API.service.AiPictureService;
import com.message.Baidu_ai_API.util.Base64Util;
import com.message.Baidu_ai_API.util.FileUtil;
import com.message.Baidu_ai_API.util.HttpUtil;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
@Service
public class AiPictureServiceImpl implements AiPictureService {
    @Override//图片转base64传给baiduapi解析后获取传回来的base64码,黑白图片上色
    public String Colourize(String fileName,String externalResourceDir) throws Exception {//转码传输到baiduapi
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize";
            System.out.println(fileName);
            // 本地文件路径
            String filePath =externalResourceDir+"\\"+fileName+".png";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            String accessToken = "24.97b658223d82fe59e4fa81196a39800c.2592000.1732771197.282335-115915927";
            String result = HttpUtil.post(url, accessToken, param);

            // 解析JSON并提取image属性
            JSONObject jsonObject = new JSONObject(result);
            String file = jsonObject.getString("image");

            // 将image属性写入文件
            String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
                writer.write(file);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println( "写入" + outputFilePath);
            return outputFilePath;
    }
    @Override//图片转base64传给baiduapi解析后获取传回来的base64码,图像风格转换
    public String styleTrans(String fileName,String externalResourceDir,Integer option) throws Exception {//转码传输到baiduapi
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans";
            // 本地文件路径
            String filePath =externalResourceDir+"\\"+fileName+".png";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String StyleName=PicStyle.fromStyleCode(option).getStyleName();//从枚举类获取风格名字选项名字
            System.out.println(StyleName);
            String param =  "option=" + StyleName +"&image=" + imgParam;
            String accessToken = "24.1ff0e598cf27db3bcfec07b0e4fb3b38.2592000.1731833877.282335-115915927";
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            // 解析JSON并提取image属性
            JSONObject jsonObject = new JSONObject(result);
            String image = jsonObject.getString("image");

            // 将image属性写入文件
            String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
                writer.write(image);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        System.out.println( "写入" + outputFilePath);
        return outputFilePath;
    }
    @Override//图片转base64传给baiduapi解析后获取传回来的base64码,图像风格转换
    public String selfie_anime(String fileName,String externalResourceDir) throws Exception {//转码传输到baiduapi
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
        // 本地文件路径
        String filePath =externalResourceDir+"\\"+fileName+".png";
        byte[] imgData = FileUtil.readFileByBytes(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param ="image=" + imgParam;
        String accessToken = "24.1ff0e598cf27db3bcfec07b0e4fb3b38.2592000.1731833877.282335-115915927";
        String result = HttpUtil.post(url, accessToken, param);
        System.out.println(result);
        // 解析JSON并提取image属性
        JSONObject jsonObject = new JSONObject(result);
        String image = jsonObject.getString("image");

        // 将image属性写入文件
        String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
            writer.write(image);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println( "写入" + outputFilePath);
        return outputFilePath;
    }
    @Override//将转存好的base64码转为图片
     public void Base64ToImage(String fileName,String txtfilePath,String filePath){
    // 输入 Base64 编码文件的路径
    String outputImagePath =filePath+"\\"+fileName+".png";
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(txtfilePath))) {
        StringBuilder base64StringBuilder = new StringBuilder();
        char[] buffer = new char[1024]; // 用于读取文件的缓冲区
        int bytesRead;

        // 按块读取 Base64 编码文件
        while ((bytesRead = reader.read(buffer)) != -1) {
            base64StringBuilder.append(buffer, 0, bytesRead);
        }
        String base64String = base64StringBuilder.toString();
        try {
            byte[] imageBytes = Base64.getDecoder().decode(base64String);
            try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
                fos.write(imageBytes);
                System.out.println("图像已成功保存到 " + outputImagePath);
            }
        } catch (IllegalArgumentException e) {
            System.err.println("解码失败，可能是因为数据不完整或格式错误: " + e.getMessage());
        }
    }
            catch (IOException e) {
        e.printStackTrace();
        System.err.println("读取或写入文件时出错: " + e.getMessage());
    }
    }
}
